package com.lzb.convert.chn;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Scanner;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import com.lzb.convert.util.ConverterUtil;
import com.lzb.demo.ExcelHelper;
import com.lzb.demo.HssfExcelHelper;
import com.lzb.demo.XssfExcelHelper;
import com.lzb.domain.CustomRow;

public class Main {

	public static final String CHN_CHAR_TO_UNICODE = "unicode";
	public static final String CHN_CHAR_TO_ENCODEURI = "encodeURI";
	public static final String FILE_SUFFIX_XLS = "xls";
	public static final String FILE_SUFFIX_XLSx = "xlsx";
	public static final String SOURCE_DIR = "demo//";
	public static final String TARGET_DIR = "done//";

	public static void main(String[] args) {
		Scanner scanner1 = new Scanner(System.in);
		try {
			String convertWay = CHN_CHAR_TO_UNICODE;
			String sheetNameOrSheetIndex = "0";
			boolean isCopyHeaderFormat = true;
			File sourceFileDirectory = new File(SOURCE_DIR);
			File[] sourceFiles = sourceFileDirectory.listFiles(new FileFilter() {
				@Override
				public boolean accept(File pathname) {
					if (StringUtils.endsWithIgnoreCase(pathname.getName(), FILE_SUFFIX_XLS) || StringUtils.endsWithIgnoreCase(pathname.getName(), FILE_SUFFIX_XLSx)) {
						return true;
					}
					return false;
				}
			});
			System.out.println("Unicode 转码，请输入\"0\" or EncodeURI 加码，请输入\"1\"？（不输入则默认为Unicode）按回车确认：");
			if (scanner1.hasNextLine()) {
				if ("1".equals(scanner1.nextLine())) {
					convertWay = CHN_CHAR_TO_ENCODEURI;
				}
			}
			System.out.println("====================美丽的分割线===========================");
			System.out.println("对哪一个sheet进行处理，输入数字？（不输入则默认为第一个）按回车确认：");
			if (scanner1.hasNextLine()) {
				String _readLine = scanner1.nextLine();
				if(StringUtils.isNumeric(_readLine) && Integer.parseInt(_readLine) > 0) {
					sheetNameOrSheetIndex = "" + (Integer.parseInt(_readLine) - 1);
				}
			}
			System.out.println("====================美丽的分割线===========================");
			System.out.println("数据是否沿用表头格式，{是:1,否:0}？（不输入则默认为\"是\"）按回车确认：");
			if (scanner1.hasNextLine()) {
				if ("0".equals(scanner1.nextLine())) {
					isCopyHeaderFormat = false;
				}
			}
			System.out.println("====================美丽的分割线===========================");
			
			if(sourceFiles != null && sourceFiles.length != 0) {
				for (File _file : sourceFiles) {
					convert(_file, convertWay, sheetNameOrSheetIndex, isCopyHeaderFormat);
				}
			}
			System.out.println("程序执行完成，可手动关闭窗口。");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(scanner1 != null) {
				scanner1.close();
			}
		}
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public static void convert(File sourceFile, String convertWay, String sheetNameOrSheetIndex,
			boolean isCopyHeaderFormat) throws Exception {
		String fileSuffix = sourceFile.getName().substring(sourceFile.getName().lastIndexOf(".") + 1, sourceFile.getName().length());
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		File targetFile = new File(TARGET_DIR + sourceFile.getName().substring(0, sourceFile.getName().lastIndexOf("."))
				+ "_" + convertWay + "_" + format.format(new Date()) + "_done" + "." + fileSuffix);
		// 这个位置应该跟excel的表头名称位置对应
		String[] fieldNames = new String[] { "promotePlanName", "promoteUnitName", "keyword", "confirmedURL",
				"keywordConverted", "promotePlanConverted", "confirmedURLConverted" };
		//可用于验证表头栏位
		String[] titles = new String[]{"推广计划名称","推广单元名称","关键词名称","已确认url","关键词加码","推广计划加码","加码url"};
		try {
			FileUtils.copyFile(sourceFile, targetFile);
		} catch (IOException e) {
			throw e;
		}
		ExcelHelper helperReader = null;
		if(FILE_SUFFIX_XLS.equalsIgnoreCase(fileSuffix)) {
			helperReader = HssfExcelHelper.getInstance(targetFile);
		} else if(FILE_SUFFIX_XLSx.equalsIgnoreCase(fileSuffix)) {
			helperReader = XssfExcelHelper.getInstance(targetFile);
		} else {
			System.out.println("未识别的文件类型[" + fileSuffix + "]");
			return;
		}
		try {
			List<CustomRow> rows = helperReader.readExcel(CustomRow.class, fieldNames, true, true, titles);
			if (rows != null && rows.size() != 0) {
				System.out.println("begin-convert:一共处理[" + rows.size() + "]条数据");
				for (CustomRow _row : rows) {
					// 原url应该以"/"结尾，如果不是，则程序自动添加
					if (StringUtils.isNotBlank(_row.getConfirmedURL()) && !_row.getConfirmedURL().endsWith("/")) {
						_row.setConfirmedURL(_row.getConfirmedURL() + "/");
					}
					if (CHN_CHAR_TO_UNICODE.equals(convertWay)) {
						_row.setKeywordConverted(ConverterUtil.chnToUnicode(StringUtils.trimToEmpty(_row.getKeyword())));
						_row.setPromotePlanConverted(ConverterUtil.chnToUnicode(StringUtils.trimToEmpty(_row.getPromotePlanName())));
						_row.setConfirmedURLConverted(_row.getConfirmedURL() + "?utm_source=Baidu&utm_medium=" +StringUtils.trimToEmpty( _row.getKeywordConverted())
										+ "&utm_campaign=" + StringUtils.trimToEmpty(_row.getPromotePlanConverted()));
					} else {
						_row.setKeywordConverted((ConverterUtil.chnToEncode(StringUtils.trimToEmpty(_row.getKeyword()))).toLowerCase());
						_row.setPromotePlanConverted((ConverterUtil.chnToEncode(StringUtils.trimToEmpty(_row.getPromotePlanName()))).toLowerCase());
						_row.setConfirmedURLConverted(_row.getConfirmedURL() + "?utm_source=Baidu&utm_medium=" + StringUtils.trimToEmpty(_row.getKeywordConverted())
										+ "&utm_campaign=" + StringUtils.trimToEmpty(_row.getPromotePlanConverted()));
					}
				}
				System.out.println("end-convert:一共处理[" + rows.size() + "]条数据");
				ExcelHelper helperWriter = null;
				if(FILE_SUFFIX_XLS.equalsIgnoreCase(fileSuffix)) {
					helperWriter = HssfExcelHelper.getInstance(targetFile);
				} else if(FILE_SUFFIX_XLSx.equalsIgnoreCase(fileSuffix)) {
					helperWriter = XssfExcelHelper.getInstance(targetFile);
				} else {
					System.out.println("未识别的文件类型[" + fileSuffix + "]");
					return;
				}
				System.out.println("begin-write-file:数据写入到文件");
				helperWriter.writeExcel(CustomRow.class, rows, fieldNames, null, sheetNameOrSheetIndex,
						isCopyHeaderFormat);
				System.out.println("end-write-file:数据写入到文件");
				System.out.println(sourceFile.getAbsolutePath() + " 转换完成，文件路径：[" + targetFile.getAbsolutePath() + "]");
				//删除demo目录文件
				FileUtils.forceDeleteOnExit(sourceFile);
			} else {
				//删除done目录的文件
				FileUtils.forceDeleteOnExit(targetFile);
			}
		} catch (Exception e) {
			throw e;
		}
	}
}
